package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.CheckBox;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.SysRole;
import com.cy.pj.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Override
    public List<SysRole> findRoles(SysRole sysRole) {
        return sysRoleDao.selectRoles(sysRole);
    }

    @Override
    public SysRole findById(Integer id) {
        return sysRoleDao.selectById(id);
    }

    @Transactional
    @Override
    public int saveRole(SysRole sysRole) {
        //新增角色自身信息
      int rows=  sysRoleDao.insertRole(sysRole);
      //新增角色菜单关系数据
        sysRoleMenuDao.insertRoleMenus(sysRole.getId(), sysRole.getMenuIds());
        return rows ;
    }

    @Override
    public int updateRole(SysRole sysRole) throws ServiceException {
        //1更新角色自身信息
       int  rows= sysRoleDao.updateRole(sysRole);
       if (rows==0)throw  new ServiceException("记录可能已经不存在");
        //2更新角色菜单关系数据
        //2.1 先删除原有关系再添加新的关系
        sysRoleMenuDao.deleteByRoleId(sysRole.getId());
        sysRoleMenuDao.insertRoleMenus(sysRole.getId(), sysRole.getMenuIds());
        return rows;
    }
    @Transactional(readOnly = true)
    @Override
    public List<CheckBox> findCheckRoles() {
        return sysRoleDao.selectCheckRoles();
    }
}
